package inet.app.view.activity;

import inet.app.R;
import inet.app.controller.database.DataBaseHandler;
import inet.app.controller.parser.Parser_Kqxs;
import inet.app.controller.request.Request;
import inet.app.model.lottery.GetLoto;
import inet.app.model.lottery.LotteryResult;
import inet.app.model.object.KqGiai_Item;
import inet.app.model.object.Veso_Item;
import inet.app.model.util.DateProc;
import inet.app.model.util.ProgressDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/*public class VesoAddNew extends BaseActivity implements OnClickListener,
 OnTouchListener*/
public class VesoAddNew extends BaseFragmentActivity implements
		OnClickListener, OnTouchListener {
	EditText etBoso, etDate;
	private TextView tvfotter, tvSpTinh, tvTitle;
	Button btXem;
	Dialog dialog;
	String khuyenkhich = "";
	Spinner spTinh;
	String trunggiai, duoi_veso, ketqua;
	LotteryResult lotteryresult;
	private DataBaseHandler db;
	private Veso_Item item_veso;
	private String date_current;
	int myYear, myMonth, myDay, myHour, myMinute;
	private ArrayList<String> list_tentinh = new ArrayList<String>();
	private ArrayList<String> list_matinh = new ArrayList<String>();
	private Request request = new Request();
	ArrayList<KqGiai_Item> arraylist = new ArrayList<KqGiai_Item>();
	private Parser_Kqxs parser = new Parser_Kqxs();
	private String matinh, tentinh;
	private ProgressDialog pdia;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.veso_screen);
		pdia = new ProgressDialog(VesoAddNew.this);
		initBase();
		initScreen();
		GetListTinhByDate(date_current);
		implement();
		addSpinner();

	}

	private void addSpinner() {
		// TODO Auto-generated method stub
		ArrayAdapter<String> arrayadapter_sptinh = new ArrayAdapter<String>(
				VesoAddNew.this, android.R.layout.simple_spinner_item,
				list_tentinh);
		arrayadapter_sptinh
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spTinh.setAdapter(arrayadapter_sptinh);
		spTinh.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> arg0, View v,
					final int pos, long id) {
				tvSpTinh.setText(" " + list_tentinh.get(pos));
				spTinh.setSelection(pos);
				matinh = list_matinh.get(pos);
				tentinh = list_tentinh.get(pos);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});
	}

	private void initScreen() {
		// TODO Auto-generated method stub
		etBoso = (EditText) findViewById(R.id.etBoso);
		etDate = (EditText) findViewById(R.id.etDate);
		spTinh = (Spinner) findViewById(R.id.spTinh);
		btXem = (Button) findViewById(R.id.btXem);
		tvSpTinh = (TextView) findViewById(R.id.tvSpTinh);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		tvTitle.setText("Thêm Vé Số");
		tvSpTinh.setOnClickListener(this);
		tvfotter = (TextView) findViewById(R.id.tvfotter);
		final Animation text_animation = AnimationUtils.loadAnimation(this,
				R.anim.custom_text_animation);
		tvfotter.startAnimation(text_animation);
		tvfotter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pdia.show();

				Intent myWebLink = new Intent(
						android.content.Intent.ACTION_VIEW);
				myWebLink.setData(Uri.parse("http://m.ole.vn/"));
				startActivity(myWebLink);
				pdia.dismiss();
			}
		});

		date_current = DateProc.Timestamp2DDMMYYYY(DateProc.createTimestamp());
		etDate.setText(date_current);
		db = new DataBaseHandler(VesoAddNew.this);
		// Set day, month, year
		myYear = Integer.parseInt(date_current.split("/")[2]);
		myMonth = Integer.parseInt(date_current.split("/")[1]);
		myDay = Integer.parseInt(date_current.split("/")[0]);
	}

	private void implement() {
		// TODO Auto-generated method stub
		btXem.setOnClickListener(this);
		etDate.setOnTouchListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btXem:
			if (!etBoso.getText().toString().equals("")) {
				pdia.show();
				sendRequest();
			} else {
				Toast.makeText(VesoAddNew.this, "Mời nhập bộ số cần dò",
						Toast.LENGTH_LONG).show();
			}
			break;
		case R.id.tvSpTinh:
			spTinh.performClick();
			break;
		default:
			break;
		}
	}

	// Dialog Loading

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN)
			switch (v.getId()) {
			case R.id.etDate:
				DatePickerDialog.OnDateSetListener myOnDateListener = new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						myYear = year;
						myMonth = monthOfYear + 1;
						myDay = dayOfMonth;
						// FORMAT DATE
						SimpleDateFormat form1 = new SimpleDateFormat(
								"dd/MM/yyyy");
						java.sql.Timestamp ts1 = DateProc.buildTimestamp(
								myYear, myMonth, myDay);
						date_current = form1.format(ts1);
						// END
						etDate.setText(date_current);
						// sendRequestList(date_current);
						GetListTinhByDate(date_current);
						addSpinner();
					}
				};
				DatePickerDialog datepicker = new DatePickerDialog(this,
						myOnDateListener, myYear, myMonth - 1, myDay);
				datepicker.show();
				break;
			default:
				break;
			}
		return false;
	}

	@SuppressWarnings("unchecked")
	private String Result_Veso(LotteryResult result, String khuyenkhich) {

		String ketquachonso = "";
		System.out.println("GIAI KHUC KHICH " + khuyenkhich);

		GetLoto getloto = new GetLoto();
		String numberfirts, numberend;
		Collection<String> cEndNumbers = getloto
				.getEndNumberOfLotteryResult(result);
		String endNumber = "";
		duoi_veso = "      " + duoi_veso;
		if (khuyenkhich.contains(duoi_veso.substring(
				duoi_veso.length() - khuyenkhich.length(), duoi_veso.length())
				.trim())) {
			ketquachonso = " Khuyến khích " + khuyenkhich;
		}
		for (Iterator<String> it = cEndNumbers.iterator(); it.hasNext();) {
			endNumber = it.next();
			String sosanh = endNumber.split(": ")[1].toString();
			System.out.println("DUOI VE SO ========>> " + duoi_veso);
			System.out.println("LENG DUOI VÉ SỐ " + duoi_veso.length());
			System.out.println("CẮT RỒI LÀ  "
					+ duoi_veso.substring(duoi_veso.length() - sosanh.length(),
							duoi_veso.length())
					+ "---LENG :"
					+ duoi_veso.substring(duoi_veso.length() - sosanh.length(),
							duoi_veso.length()).length());
			System.out.println("SO SANH =============>> " + sosanh);
			System.out.println("REPLACE ALL : "
					+ duoi_veso.substring(duoi_veso.length() - sosanh.length(),
							duoi_veso.length()).trim());
			System.out.println("DUOI VE SO >LENGTH " + duoi_veso.length());
			if (duoi_veso.substring(duoi_veso.length() - sosanh.length(),
					duoi_veso.length()).contains(sosanh)) {
				ketquachonso += " " + endNumber;
			}
		}
		return ketquachonso;
	}

	private void GetListTinhByDate(String date) {

		System.out.println("NGAFY LAF :" + date);
		String temp[];
		temp = date.split("/");
		final Calendar cal_thu = Calendar.getInstance();
		cal_thu.set(Integer.parseInt(temp[2]), Integer.parseInt(temp[1]) - 1,
				Integer.parseInt(temp[0].substring(temp[0].length() - 2,
						temp[0].length())));
		int thuofngay = cal_thu.get(Calendar.DAY_OF_WEEK);
		System.out.println("THỨ CỦA NGÀY LÀ " + thuofngay);
		list_matinh.clear();
		list_tentinh.clear();

		if (thuofngay == 1) {
			list_matinh.add("XSTD");
			list_matinh.add("XSKH");
			list_matinh.add("XSKT");

			list_matinh.add("XSTG");
			list_matinh.add("XSKG");
			list_matinh.add("XSDL");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Khánh Hòa");
			list_tentinh.add("Kon Tum");

			list_tentinh.add("Tiền Giang");
			list_tentinh.add("Kiên Giang");
			list_tentinh.add("Đà Lạt");

		}

		else if (thuofngay == 7) {
			list_matinh.add("XSTD");
			list_matinh.add("XSDNG");
			list_matinh.add("XSQNI");
			list_matinh.add("XSDNO");
			list_matinh.add("XSHCM");
			list_matinh.add("XSLA");
			list_matinh.add("XSBP");
			list_matinh.add("XSHG");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Đà Nẵng");
			list_tentinh.add("Quảng Ngãi");
			list_tentinh.add("Đắc Nông");

			list_tentinh.add("Hồ Chí Minh");
			list_tentinh.add("Long An");
			list_tentinh.add("Bình Phước");
			list_tentinh.add("Hà Giang");
		}

		else if (thuofngay == 6) {
			list_matinh.add("XSTD");
			list_matinh.add("XSGL");
			list_matinh.add("XSNT");

			list_matinh.add("XSVL");
			list_matinh.add("XSBD");
			list_matinh.add("XSTV");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Gia Lai");
			list_tentinh.add("Ninh Thuận");

			list_tentinh.add("Vĩnh Long");
			list_tentinh.add("Bình Dương");
			list_tentinh.add("Trà Vinh");
		} else if (thuofngay == 5) {
			list_matinh.add("XSTD");
			list_matinh.add("XSBDH");
			list_matinh.add("XSQB");
			list_matinh.add("XSQT");
			list_matinh.add("XSAG");
			list_matinh.add("XSTN");
			list_matinh.add("XSBTH");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Bình Định");
			list_tentinh.add("Quảng Bình");
			list_tentinh.add("Quảng Trị");

			list_tentinh.add("An Giang");
			list_tentinh.add("Tây Ninh");
			list_tentinh.add("Bình Thuận");
		} else if (thuofngay == 4) {
			list_matinh.add("XSTD");
			list_matinh.add("XSKH");
			list_matinh.add("XSDNG");
			list_matinh.add("XSDN");
			list_matinh.add("XSST");
			list_matinh.add("XSCT");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Khánh Hòa");
			list_tentinh.add("Đà Nẵng");

			list_tentinh.add("Đồng Nai");
			list_tentinh.add("Sóc Trăng");
			list_tentinh.add("Cần Thơ");
		} else if (thuofngay == 3) {
			list_matinh.add("XSTD");
			list_matinh.add("XSDLK");
			list_matinh.add("XSQNM");
			list_matinh.add("XSBTR");
			list_matinh.add("XSVT");
			list_matinh.add("XSBL");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Đắc Lăk");
			list_tentinh.add("Quảng Nam");

			list_tentinh.add("Bến Tre");
			list_tentinh.add("Vũng Tàu");
			list_tentinh.add("Bạc Liêu");
		} else if (thuofngay == 2) {

			list_matinh.add("XSTD");
			list_matinh.add("XSPY");
			list_matinh.add("XSTTH");

			list_matinh.add("XSHCM");
			list_matinh.add("XSDT");
			list_matinh.add("XSCM");

			list_tentinh.add("Thủ Đô");
			list_tentinh.add("Phú Yên");
			list_tentinh.add("Thừa Thiên Huế");

			list_tentinh.add("Hồ Chí Minh");
			list_tentinh.add("Đồng Tháp");
			list_tentinh.add("Cà Mau");
		}

	}

	public void sendRequest() {
		AsyncTask<Void, Integer, Void> myTask = new AsyncTask<Void, Integer, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				// Request
				duoi_veso = etBoso.getText().toString();
				arraylist = parser.getList_Mt(request.getkqxs(matinh, etDate
						.getText().toString(), etDate.getText().toString()));
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				super.onPreExecute();
				if (arraylist != null) {
					System.out.println("CHAY VÀO ĐÂY ");
					if (!arraylist.get(0).getDate()
							.equals(etDate.getText().toString())) {
						System.out.println("chay vao day 1");
						ketqua = "Chưa có kết quả";
					} else {
						System.out.println("chay vao day 2");
						lotteryresult = new LotteryResult(arraylist.get(0)
								.getGiaidb(), arraylist.get(0).getGiai1(),
								arraylist.get(0).getGiai2(), arraylist.get(0)
										.getGiai3(), arraylist.get(0)
										.getGiai4(), arraylist.get(0)
										.getGiai5(), arraylist.get(0)
										.getGiai6(), arraylist.get(0)
										.getGiai7(), arraylist.get(0)
										.getGiai8());

						khuyenkhich = arraylist
								.get(0)
								.getGiaidb()
								.substring(
										arraylist.get(0).getGiaidb().length() - 2);

						ketqua = Result_Veso(lotteryresult, khuyenkhich);
						if (ketqua.equals("")) {
							ketqua = "Không trúng giải";
						}
					}
				} else {
					System.out.println("Không chyaj tao ");
					ketqua = "Chưa có kết quả";
				}

				System.out.println("KẾT QUẢ LÀ " + ketqua);
				Intent intentXem = new Intent(VesoAddNew.this, VesoList.class);
				item_veso = new Veso_Item(etBoso.getText().toString(), matinh,
						etDate.getText().toString(), ketqua, tentinh);
				if (item_veso != null)
					db.insertVeSo(item_veso);
				// SENDDATA
				String data_send = etBoso.getText().toString() + "-" + matinh
						+ "-" + etDate.getText().toString() + "-" + ketqua
						+ "-" + tentinh;
				Bundle rb = new Bundle();
				rb.putString("datasend", data_send);
				intentXem.putExtras(rb);
				startActivity(intentXem);
				pdia.dismiss();
			}
		};
		myTask.execute();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	public void onResume() {

		if (((MyApp) getApplication()).isKill()) {
			finish();
		}

		else {
			((MyApp) getApplication()).setRunning(true);
		}
		super.onResume();
	}
}
